<template>
  <ekDialog v-model="ekVisiable" title="推广二维码" @submit="handleSubmit">
    <!-- 二维码说明 -->
    <div style="padding: 20px; text-align: left; color: #909399">
      <p style="font-size: 16px">
        每个推广二维码唯一且长期有效，用户通过扫二维码，并登录注册用户，成为推广员下面的用户。
      </p>
    </div>
    <div style="padding: 20px">
      <div ref="qrCodeCanvas" v-if="ekVisiable"></div>
    </div>
    <div style="padding: 0px 20px; text-align: left">
      <el-button type="primary" @click="download()">下载</el-button>
    </div>
  </ekDialog>
</template>

<script setup>
import {
  watch,
  getCurrentInstance,
  computed,
  reactive,
  ref,
  defineEmits,
  onMounted,
  nextTick,
} from "vue";

import ekDialog from "@/components/business/ekDialog/index.vue";
import QRCode from "qrcodejs2";

const props = defineProps({
  // 显示隐藏
  visiable: {
    type: Boolean,
    default: false,
  },
  rowId: {
    type: [String, Number],
    default: "",
  },
});
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
const { $storage, $http, $ekLoading, $ekMessage } = globalProperties;

const emit = defineEmits(["update:visiable", "submit"]);

// 是否显示
const ekVisiable = computed({
  get() {
    return props.visiable;
  },
  set(value) {
    emit("update:visiable", value);
  },
});

const qrCodeCanvas = ref(null);

const init = async () => {
  nextTick(() => {
    try {
      const url = `${process.env.QRS_CODE_URL}?id=${props.rowId}`;
      new QRCode(qrCodeCanvas.value, {
        text: url, // 二维码承载信息
        width: 320,
        height: 320,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H, // 容错级别
      });
    } catch (err) {
      console.error(err, "errerrerrerr");
    }
  });
};
const download = () => {
  console.log(qrCodeCanvas.value.querySelector("canvas"), "qrCodeCanvas.value");
  const link = qrCodeCanvas.value
    .querySelector("canvas")
    .toDataURL("image/png");
  const filename = "Qrcode" + props.rowId;

  // Download
  let oA = document.createElement("a");
  oA.download = filename; // 设置下载的文件名，默认是'下载'
  oA.href = link;
  document.body.appendChild(oA);
  oA.click();
  oA.remove();
};
watch(
  () => props.visiable,
  (val) => {
    if (val) {
      init();
    }
  }
);
</script>
